//******************************************************************
//******************************************************************
//**********          ANts Peer To Peer Sources        *************
//
// ANts P2P realizes a third generation P2P net. It protects your
// privacy while you are connected and makes you not trackable, hiding
// your identity (ip) and crypting everything you are sending/receiving
// from others.

// Copyright (C) 2004  Roberto Rossi

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


package ants.p2p;

import java.net.*;
import java.io.*;
import com.jcraft.jzlib.*;
import org.apache.log4j.*;
import ants.p2p.messages.security.*;
import ants.p2p.utils.net.*;

public class TCPDirectServerThread extends Thread{
  Socket local;
  Ant ant;

  private static Logger _logger = Logger.getLogger(TCPDirectServerThread.class.getName());

  public TCPDirectServerThread (Socket local, Ant ant){
    this.ant = ant;
    this.local = local;
  }

  public void run(){
    try{
      BandwidthFilterIn bfIn = new BandwidthFilterIn(local.getInputStream());
      ZInputStream zIn = new ZInputStream(bfIn);
      ObjectInputStream objIn = new ObjectInputStream(zIn);
      String remoteAddress = (String)objIn.readObject();
      if(remoteAddress.startsWith("/")) remoteAddress = remoteAddress.substring(1);
      Object obj = objIn.readObject();
      NeighbourAnt.totalCompressedSizeIn += zIn.getTotalIn();
      NeighbourAnt.totalUncompressionSizeIn += zIn.getTotalOut();
      long size = zIn.getTotalIn();
      objIn.close();
      if (obj instanceof NetModificationAlert && ((NetModificationAlert) obj).getVersion().equals(Ant.getProtocolVersion())){
        if(!remoteAddress.equals("")){
          Neighbour requirer = new DirectNeighbour(remoteAddress, ant);
          _logger.info("Procesing net modification from DC " + requirer);
          this.ant.processNetModificationAlert( (NetModificationAlert) obj, requirer);
        }
      }
      else if (obj instanceof Message && ((Message) obj).getVersion().equals(Ant.getProtocolVersion())) {
          Message m = (Message) obj;
          NeighbourAnt.updateInStats(m, size);
          if (ant.getIdent().equals(m.getSource()) || !MessageSigner.getInstance().verifySignature(m, m.getSource())) return;
          _logger.debug(remoteAddress + ": DCMessage received ID "+m+" From: "+m.getSource()+" To: "+m.getDest());
          if (!remoteAddress.equals("") && ant.routingTable.get(m.getSource()) != null) {
            RoutingTableElement rte = (RoutingTableElement)ant.routingTable.get(m.getSource());
            rte.addTracedRoute(remoteAddress);
          }
          else if(!remoteAddress.equals("")){
            RoutingTableElement rte = new RoutingTableElement();
            rte.addTracedRoute(remoteAddress);
            ant.routingTable.put(m.getSource(), rte);
          }
          if(!remoteAddress.equals(""))
            ant.activateNewRouterProcess(m, remoteAddress);
          else
            ant.activateNewRouterProcess(m, this.ant.getIdent());
      }
    }catch(Exception e){
      _logger.debug("TCP Direct Server thread exception: ",e);
    }
  }
}
